import os
from pathlib import Path

import requests


def fetch_releases(repo: str, token: str | None = None):
    url = f"https://api.github.com/repos/{repo}/releases"
    headers = {"Accept": "application/vnd.github+json"}
    if token:
        headers["Authorization"] = f"Bearer {token}"
    response = requests.get(url, headers=headers, timeout=30)
    response.raise_for_status()
    return response.json()


def write_changelog(releases):
    path = Path("docs/changelog.md")
    lines = [
        "# Changelog",
        "",
        "_This file is automatically generated from GitHub releases._",
        "",
    ]
    for rel in releases:
        tag = rel.get("tag_name") or ""
        name = rel.get("name") or tag
        date = (rel.get("published_at") or "")[:10]
        body = rel.get("body") or ""
        header = f"## {name} - {date}".strip()
        lines.append(header)
        if body:
            lines.append("")
            lines.extend(body.splitlines())
        lines.append("")
    path.write_text("\n".join(lines))


def main() -> None:
    repo = os.getenv("GITHUB_REPOSITORY", "Blaizzy/mlx-vlm")
    token = os.getenv("CHANGELOG_TOKEN")
    releases = fetch_releases(repo, token)
    write_changelog(releases)


if __name__ == "__main__":
    main()
